% Analysis Reduction Error 
clc;
clear all;
close all;
%% function analysis_red_err_alpha(lower,upper,m,n,r,k, alpha)
m = 6; n = 6; r = 6; k = 2;
lower = 0;
upper = 0.9999999999;
%compute correction const. with uniform and opt.
const_uniform = ccm_rd(m, n, r, k, 0.5);
const_opt = 0.5 * ccm_rd(m, n, r, k, 1); 

step_a = 2^(-m);
step_b = 2^(-n);
%get the probability of a and b
num = (round((upper-lower)/step_a) + 1)*(round((upper-lower)/step_b) + 1);
%print rows

alpha = 0:0.05:1;
L = length(alpha);
err_uniform_alpha = zeros(1, L);
err_opt_alpha = zeros(1, L);

%%
for i = 1:L %for each probability
    %find the Bayes
    i
    i_alpha = alpha(i);    
    index = 0;
    for a = lower:step_a:upper
        for b = lower:step_b:upper
            index = index + 1
            p_ab = prob_joint(a, b, m, n, i_alpha);%probability of a,b        
            %answers true, uniform constant and opt. constant
            ans_true = a * b;
            ans_uniform = trunc_mult(a, b, const_uniform, m, n, r, k);
            ans_opt = trunc_mult(a, b, const_opt, m, n, r, k);
            %errors
            err_uniform = ans_uniform - ans_true;
            err_opt = ans_opt - ans_true;
            %average errors
            err_uniform_alpha(i) = err_uniform_alpha(i) + err_uniform * p_ab;
            err_opt_alpha(i) = err_opt_alpha(i) + err_opt * p_ab;
        end
    end
end

%% Display results
figure(1);
plot(alpha,abs(err_uniform_alpha), alpha, abs(err_opt_alpha)); 
legend('Uniform', 'Optimal');
